<template>
	<view class="z-box">
		<view class="title">吉林省<br />农产品土壤采样平台</view>
		<view class="login-box">
			<u-input class="ipt" placeholder="请输入用户名" border="surround" v-model="loginForm.userName" fontSize="16"
				prefixIcon="account" shape="circle"></u-input>
			<u-input class="ipt pwd" placeholder="请输入密码" border="surround" v-model="loginForm.password" fontSize="16"
				prefixIcon="lock" shape="circle" :password="true"></u-input>
			<u-button size="large" type="primary" shape="circle" :disabled="isLogining" text="登录"
				@click="login"></u-button>
		</view>
		<u-notify ref="notify"></u-notify>
	</view>
</template>

<script>
	// vue vuex
	import {
		mapMutations
	} from 'vuex'
	// tools
	import Util from '@/utils/index.js';
	// mixins
	import NotifyMix from '@/mixins/notify-fix.js'
	// api
	import API from '@/api/index.js'
	export default {
		mixins: [NotifyMix],
		data() {
			return {
				loginForm: {
					userName: '',
					password: '',
					moduleCode: 'sampling'
				},
				isLogining: false,
				setIntervalInfo: false
			}
		},
		methods: {
			...mapMutations({
				setToken: 'user/setToken',
				setUserInfo: 'user/setUserInfo',
				setDicts: 'dict/setDicts',
				setStatusBarHeight: 'system/setStatusBarHeight',
				setWindowHeight: 'system/setWindowHeight'
			}),
			init() {
				const that = this
				uni.getSystemInfo({
					success: (res) => {
						that.setStatusBarHeight(res.statusBarHeight)
						that.setWindowHeight(res.windowHeight)
						// #ifdef APP-PLUS
						that.checkUpdate()
						// #endif
					},
					fail(err) {
						uni.showToast({
							title: '应用初始化失败',
							icon: 'error',
							duration: 3000
						})
					}
				})
			},
			checkUpdate() {
				const that = this
				plus.runtime.getProperty(plus.runtime.appid, (inf) => {
					const clientVersion = inf.version
					API.SysUniappVersionApi.getLastVersion().then(res => {
							if (res.code !== 200 || !res.data) {
								uni.showToast({
									title: '获取新版本失败',
									icon: 'error',
									duration: 3000
								});
								return;
							}
							const serverVersion = res.data.remark
							console.log(serverVersion, clientVersion, 'content')
							if (!(clientVersion < serverVersion)) {
								return
							}
							const apkUrl = res.data.path;
							let content = '现版本：' + clientVersion + '\n' +
								'新版本：' + serverVersion + '\n' +
								'为不影响使用，请立即更新\n\n';
							that.updateApp(content, apkUrl)
						})
						.catch(err => {
							console.log(err, 'err')
							uni.showToast({
								title: '获取新版本失败',
								icon: 'error',
								duration: 3000
							});
						})
				});
			},
			updateApp(content, apkUrl) {
				const that = this
				uni.showModal({
					title: '发现新版本',
					content: content,
					confirmText: '确认',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '更新中请等待...'
							})
							clearInterval(this.setIntervalInfo)
							this.setIntervalInfo = false
							const downloadTask = plus.downloader.createDownload(
								apkUrl, {
									timeout: 120,
									retry: 0,
									retryInterval: 0
								},
								function(data, status) {
									if (status == 200) {
										plus.runtime.install(
											downloadTask.filename, {},
											function() {
												uni.hideLoading()
												uni.showToast({
													title: '安装成功请重启',
													icon: 'success'
												});
											},
											function(error) {
												uni.hideLoading()
												uni.showToast({
													title: '安装失败',
													icon: 'error'
												})
											}
										)
									} else {
										uni.hideLoading()
										uni.showToast({
											title: '下载更新包失败',
											icon: 'error'
										})
									}
								}
							)
							downloadTask.start()
						}
					}
				});
			},
			initAccount() {
				const account = Util.StorageUtil.get('JDWN_ACCOUNT')
				if (account) {
					this.loginForm.userName = account.userName
					this.loginForm.password = account.password
				}
			},
			async login() {
				this.isLogining = true
				if (Util.StringUtil.isEmpty(this.loginForm.userName) || Util.StringUtil.isEmpty(this.loginForm
						.password)) {
					this.notifyFail('用户名或密码为空')
					this.isLogining = false
					return
				}
				uni.showLoading()
				let res = await API.AuthApi.login({
					userName: this.loginForm.userName,
					password: Util.CryptoJS.SHA256(this.loginForm.password).toString(),
					moduleCode: 'SAMPLING'
				})
				if (res.code !== 200 || !res.data) {
					this.notifyFail('登录失败')
					uni.hideLoading()
					this.isLogining = false
					return
				}
				this.setToken(res.data.token)
				Util.StorageUtil.save('JDWN_ACCOUNT', {
					userName: this.loginForm.userName,
					password: this.loginForm.password
				})
				res = await API.AuthApi.getUserInfo()
				uni.setStorageSync('roles',res.data.roles[0].code)
				if (res.code !== 200 || !res.data) {
					this.notifyFail('获取我的信息失败')
					uni.hideLoading()
					this.isLogining = false
					return
				}
				this.setUserInfo(res.data)
				res = await API.SysDictItemApi.getAllDict({})
				if (res.code !== 200 || !res.data) {
					this.notifyFail('获取字典信息失败')
					uni.hideLoading()
					this.isLogining = false
					return
				}
				this.setDicts(res.data)
				this.notifyOk('登录成功')
				uni.hideLoading()
				this.isLogining = false
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		mounted() {
			this.initAccount()
			const that = this
			that.init()
			this.setIntervalInfo = setInterval(() => {
				that.init()
			}, 18000000)

		}
	}
</script>

<style lang="scss" scoped>
	.z-box {
		width: 100vw;
		height: 100vh;
		background-image: url("@/static/login-bg.jpg");
		background-repeat: no-repeat;
		background-position: center center;
		background-size: cover;
		padding-top: 20vh;

		.ipt {
			height: 44px;

			&.pwd {
				margin-top: 20px;
				margin-bottom: 35px;
			}
		}

		.title {
			font-size: 30px;
			font-weight: bold;
			text-align: center;
			color: #fff;
		}

		.login-box {
			width: 70vw;
			margin: 0 auto;
			margin-top: 6vh;
		}

		::v-deep .u-input {
			background-color: #fff;
		}
	}
</style>